package com.xin.auto.lib.base;

import android.content.Context;
import android.os.Environment;
import android.os.storage.StorageManager;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import me.jahnen.libaums.core.fs.UsbFile;
import me.jahnen.libaums.core.fs.UsbFileOutputStream;

public class FileUtils {

    public static List<String> getUsbPaths(Context cxt) {
        List<String> usbPaths = new ArrayList<>();
        try {
            StorageManager srgMgr = (StorageManager) cxt.getSystemService(Context.STORAGE_SERVICE);
            Class<StorageManager> srgMgrClass = StorageManager.class;
            String[] paths = (String[]) srgMgrClass.getMethod("getVolumePaths").invoke(srgMgr);
            for (String path : paths) {
                Object volumeState = srgMgrClass.getMethod("getVolumeState", String.class).invoke(srgMgr, path);
                if (!path.contains("emulated") && Environment.MEDIA_MOUNTED.equals(volumeState))
                    usbPaths.add(path);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return usbPaths;
    }

    public static boolean copySdcardFile(UsbFile tocFolder, String fromFile) {
        try {
            InputStream inusb = new FileInputStream(fromFile);
            UsbFileOutputStream fosto = new UsbFileOutputStream(tocFolder, true);

            byte bt[] = new byte[1024 * 10];
            int c;
            while ((c = inusb.read(bt)) != -1) {
                fosto.write(bt, 0, c);
            }
            fosto.flush();
            inusb.close();
            fosto.close();
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return false;
    }

    //删除源文件
    private void deleteFile(File file) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                File f = files[i];
                deleteFile(f);
            }
        } else if (file.exists()) {
            file.delete();
        }
    }

    public static List<String> mediaFileList = new ArrayList<>();

    public static void setMediaFiles(List<String> mediaFiles) {
        mediaFileList = mediaFiles;
    }
}
